



type Clean = () => void;

export function schedulerCallbackOnNextLongTick(callback: () => void): Clean {
  let idlId: number = null, timeoutId: NodeJS.Timeout = null;

  timeoutId = setTimeout(() => {
    clean();
    timeoutId = setTimeout(() => {
      clean();

      idlId = requestIdleCallback(() => {
        clean();

        idlId = requestIdleCallback(() => {
          clean();
          callback();
        });
      });
    });
  });

  const clean = () => {
    if (timeoutId !== null) {
      clearTimeout(timeoutId);
      timeoutId = null;
    }

    if (idlId !== null) {
      cancelIdleCallback(idlId);
      idlId = null;
    }
  };

  return clean;
}


export function schedulerCallbackOnTimeout(callback: () => void, ms?: number): Clean {
  let timeoutId: NodeJS.Timeout = null;

  timeoutId = setTimeout(() => {
    clean();
    callback();
  }, ms);

  const clean = () => {
    if (timeoutId !== null) {
      clearTimeout(timeoutId);
      timeoutId = null;
    }
  };

  return clean;
}